<!-- 出库订单管理 -->
<template>
    <div class="outbound-order-container">
        <div class="page-box">
            <div class="page-title">
                {{ '补库订单管理' }}
            </div>

            <div class="page-search">
                <div class="search-box" :style="{ height: IsHeight }">
                    <el-input v-model="pageData.keywords" placeholder="补库单号/客户"
                        style="width: 200px; margin-right: 10px" suffix-icon="search" @input="handleSearchChange" />
                    <!-- 筛选状态 -->
                    <h3 style="margin-right: 10px;margin-left: 10px;">显示：</h3>

                    <!-- 状态筛选按钮组 -->
                    <div class="status-filter">
                        <el-button :class="['status-btn', { active: pageData.status === '' }]"
                            @click="handleStatusFilter('')">
                            全部
                        </el-button>
                        <el-button :class="['status-btn', { active: pageData.status === '0' }]"
                            @click="handleStatusFilter('0')">
                            待提交
                        </el-button>
                        <el-button :class="['status-btn', { active: pageData.status === '1' }]"
                            @click="handleStatusFilter('1')">
                            审核中
                        </el-button>
                        <el-button :class="['status-btn', { active: pageData.status === '2' }]"
                            @click="handleStatusFilter('2')">
                            审核完成
                        </el-button>
                        <el-button :class="['status-btn', { active: pageData.status === '3' }]"
                            @click="handleStatusFilter('3')">
                            审核拒绝
                        </el-button>
                    </div>
                </div>
                <div class="search-btn">
                    <div class="btn_item" @click="handleClickHeight">
                        <img class="btn_img" src="@/assets/sx.png" alt="" />
                        <span> 高级筛选 </span>
                    </div>
                </div>
            </div>
            <div class="search-btn-right">
                <el-button color="#626aef" type="primary" @click="handleClickAdd"> 新增 </el-button>
            </div>
            <!-- 批量提交审核 -->
            <div class="batch-operations">
                <div class="batch-info" v-if="selectedRows.length > 0">
                    已选择 {{ selectedRows.length }} 项
                </div>
                <el-button color="#626aef" type="primary" @click="handleClickSubmitAudit" 
                           :disabled="selectedRows.length === 0"> 
                    批量提交审核 ({{ selectedRows.length }})
                </el-button>
                <el-button v-if="selectedRows.length > 0" @click="clearSelection">
                    取消选择
                </el-button>
            </div>
        </div>

        <div class="table-box">

            <el-table :data="tabeData" style="width: 100%" v-loading="loading" border height="700px"
                      @selection-change="handleSelectionChange" ref="tableRef">  
                <el-table-column type="selection" width="55" />
                <el-table-column align="center" prop="order_no" label="出库单号" width="auto" />
                <el-table-column align="center" prop="total_amount" label="出库金额（元）" width="auto">
                </el-table-column>
                <el-table-column align="center" prop="created_at" label="下单日期" width="auto">
                </el-table-column>
                <el-table-column align="center" prop="delivery_date" label="交货日期" width="auto" />
                <el-table-column align="center" prop="type_text" label="订单类型" width="auto" />
                <el-table-column align="center" prop="customer_name" label="客户名称" width="auto" />
                <el-table-column align="center" prop="customer_phone" label="联系电话" width="auto" />
                <el-table-column align="center" prop="category_name" label="地区" width="auto">
                    <template #default="scope">
                        <span>{{ scope.row.province + ' 省' + scope.row.city + ' 市' + scope.row.area + ' 区' }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="address" label="详细地址" width="auto" />
                <el-table-column align="center" prop="status_text" label="状态" width="90">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.status)" size="small">
                            {{ scope.row.status_text }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="contact_name" label="出库负责人" width="auto" />
                <el-table-column align="center" prop="contact_phone" label="负责人电话" width="auto" />
                <el-table-column align="center" prop="creator_name" label="创建人" width="auto" />
                <el-table-column align="center" prop="note" label="备注" width="auto" />
                <el-table-column align="center" prop="created_at" label="创建时间" width="auto" />
                <el-table-column fixed="right" label="操作" min-width="260" prop="id" align="center">
                    <template #default="scope">
                        <div class="btn-box">
                            <el-button plain size="small" type="primary" @click="handleClickEdit(scope.row)" :disabled="scope.row.status !== 0 && scope.row.status !== 3" class="action-btn"> 编辑
                            </el-button>
                            <el-button plain size="small" type="danger" @click="handleClickDelete(scope.row)" :disabled="scope.row.status !== 0 && scope.row.status !== 3" class="action-btn"> 删除
                            </el-button>
                            <el-button plain size="small" type="success" @click="handleClickDetails(scope.row)" class="action-btn detail-btn"> 详情
                            </el-button>
                            <el-button plain size="small" type="primary" @click="handleSubmitAudit([scope.row.id])"
                                       :disabled="!canSubmitAudit(scope.row)" class="action-btn"> 提交审核
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <Pagination class="pagination" @pageSize="pageSize" @getPage="getPage" :page="pageData.page"
            :page-size="pageData.page_size" :total="total" />
        <!-- 新增出库 -->
        <AddOutboundOrder ref="AddedOutboundRef" @init="getAlltabeData" />
        <!-- 出库详情 -->
        <DetailsOutboundOrder v-model:dialogVisible="DetailsOutboundOrderVisible" :dialogRow="dialogRow" />
    </div>
</template>

<script setup lang="ts">
import api from "@/api";
import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import Pagination from "@/components/Pagination.vue";
import AddOutboundOrder from "./components/AddOutboundOrder/AddOutboundOrder.vue";
import DetailsOutboundOrder from "./components/DetailsOutboundOrder.vue";
import { ElMessage, ElMessageBox } from "element-plus";
const router = useRouter();
//  新增出库
const AddedOutboundRef = ref<any>(null);
// 表格引用
const tableRef = ref<any>(null);
// 选中的行数据
const selectedRows = ref<any[]>([]);
// 出库详情
let IsHeight = ref<number | string>(0);
const search = ref<string>('');
//  -----------------出库详情抽屉
//  出库详情
const DetailsOutboundOrderVisible = ref<boolean>(false);
// 定义仓库数据类型
interface Warehouse {
    id: string | number;
    title: string;
    code: string;
    house_type?: string;
    house_type_name?: string;
    category_name?: string;
    manager?: string;
    phone?: string;
    address?: string;
    remark?: string;
    parent_id?: string | number;
    parent_name?: string;
    children?: Warehouse[];
    create_time?: string;
    creator?: string;
    rowNumber?: number;
}
// 出库订单详情
let dialogRow = ref<Warehouse>({} as Warehouse);
//  -----------------列表数据
const pageData = ref({
    page_size: 10,
    page: 1,
    keywords: "",
    status: "", //订单状态 ""=全部 0=待提交 1=审核中 2=审核通过 3=审核拒绝
    customer_id: "",
});
const total = ref(0);
const tabeData = ref([]);

// 侦听动态分页
watch(
    () => {
        return pageData.value;
    },
    () => {
        getAlltabeData();
    },
    { deep: true }
);

let nub = ref<number>(0);
const handleClickHeight = () => {
    nub.value++;
    if (nub.value % 2 == 1) {
        IsHeight.value = '50px';
    } else {
        IsHeight.value = '0px';
    }
}

const pageSize = (e: number) => {
    pageData.value.page_size = e
}
const getPage = (e: number) => {
    pageData.value.page = e
}

// 状态筛选处理
const handleStatusFilter = (status: string) => {
    pageData.value.status = status;
    pageData.value.page = 1; // 重置到第一页
    console.log('筛选状态:', status === '' ? '全部' : status);
};

// 搜索变化处理（防抖）
const handleSearchChange = () => {
    pageData.value.page = 1; // 重置到第一页
    // 防抖处理
    setTimeout(() => {
        getAlltabeData();
    }, 300);
};

// 获取状态对应的标签类型
const getStatusType = (status: string | number) => {
    switch (String(status)) {
        case '0':
            return 'info';     // 待提交 - 灰色
        case '1':
            return 'warning';  // 审核中 - 橙色
        case '2':
            return 'success';  // 审核完成 - 绿色
        case '3':
            return 'danger';   // 审核拒绝 - 红色
        default:
            return '';
    }
};

// 处理表格选中变化
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection;
    console.log('选中的出库订单:', selectedRows.value);
};

// 清空选择
const clearSelection = () => {
    tableRef.value?.clearSelection();
    selectedRows.value = [];
};

// 判断订单是否可以提交审核
const canSubmitAudit = (row: any) => {
    // 只有待提交状态(0)和审核失败（3）的订单才能提交审核
    return row.status === 0 || row.status === 3;  
};

// 批量提交审核
const handleClickSubmitAudit = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要提交审核的出库订单');
        return;
    }
    
    // 过滤出可以提交审核的订单
    const validRows = selectedRows.value.filter(row => canSubmitAudit(row));
    
    if (validRows.length === 0) {
        ElMessage.warning('选中的订单中没有可以提交审核的订单（只有待提交状态的订单可以提交审核）');
        return;
    }
    
    if (validRows.length !== selectedRows.value.length) {
        ElMessage.warning(`选中的 ${selectedRows.value.length} 个订单中，只有 ${validRows.length} 个可以提交审核`);
    }
    
    const ids = validRows.map(row => row.id);
    submitAuditRequest(ids);
};

// 提交审核请求（统一处理单个和批量）
const submitAuditRequest = async (ids: number[]) => {
    try {
        await ElMessageBox.confirm(
            `确定要提交选中的 ${ids.length} 个出库订单进行审核吗？`,
            '提交审核确认',
            {
                confirmButtonText: '确定提交',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );

        console.log('提交审核的订单ID数组:', ids);

        const res = await api.Outbound.submitAudit({
            ids: ids
        });

        if (res.code == 200) {
            ElMessage.success(`成功提交 ${ids.length} 个出库订单进行审核`);
            // 清空选择
            clearSelection();
            // 刷新列表
            getAlltabeData();
        } else {
            ElMessage.error(res.message || '提交审核失败');
        }
    } catch (error) {
        console.log('用户取消提交审核');
    }
};

// 提交审核（修改原有函数支持数组参数）
const handleSubmitAudit = async (ids: number[]) => {
    submitAuditRequest(ids);
};

onMounted(() => {
    getAlltabeData();
})

// 获取出库订单列表 
const getAlltabeData = async () => {
    try {
        const res = await api.Outbound.getoutboundOrderList({
            ...pageData.value,
        });

        console.log('出库订单列表:', res);

        if (res.code == 200) {
            tabeData.value = res.data.data;
            total.value = res.data.pager.total_records ;
        }
    } catch (error) {
        console.error('获取出库订单列表失败:', error);
        ElMessage.error('获取列表失败');
    }
};

const loading = ref(false);

//  新增出库订单
const handleClickAdd = () => {
    AddedOutboundRef.value.openLoading();
}



// 删除出库订单
const handleClickDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除此出库订单吗？',
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );

        // TODO: 调用删除API
        // const res = await api.Outbound.deleteoutboundOrder({ id: row.id });
        // if (res.code === 200) {
        //     ElMessage.success('删除成功');
        //     getAlltabeData();
        // }

        ElMessage.success('删除功能待实现');
        console.log('删除订单:', row);

    } catch (error) {
        console.log('取消删除');
    }
};

// 编辑出库订单
const handleClickEdit = async (row: any) => {
    const res = await api.Outbound.getoutboundOrderDetails({ id: row.id });
    if (res.code == 200) {
        AddedOutboundRef.value.openLoading(res.data);
    }
    console.log('编辑订单:', res.data);
};

//  打开出库详情抽屉
const handleClickDetails = async (row: any) => {
    // 获取出库订单详情
    const res = await api.Outbound.getoutboundOrderDetails({ id: row.id });
    if (res.code == 200) {
        DetailsOutboundOrderVisible.value = true;
        dialogRow.value = res.data;
        console.log('查看订单详情:', res.data);
    }
}
</script>

<style lang="scss" scoped>
.btn-box {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px; // 增加按钮间距
    flex-wrap: wrap; // 允许换行，适配小屏幕
}

// 操作按钮样式优化
.action-btn {
    min-width: 60px !important; // 确保最小宽度
    padding: 8px 12px !important; // 增加内边距，扩大点击区域
    margin: 2px !important; // 增加外边距，防止误触
    font-size: 12px !important;
    border-radius: 4px !important;

    // 确保按钮有足够的点击区域
    &:hover {
        transform: scale(1.02); // 轻微放大效果，提供视觉反馈
        transition: all 0.2s ease;
    }
}

// 详情按钮特殊优化（重点针对拒绝状态的订单）
.detail-btn {
    min-width: 65px !important; // 详情按钮稍微宽一点
    padding: 10px 15px !important; // 更大的内边距
    font-weight: 500 !important;

    // 在小屏幕上进一步优化
    @media (max-width: 1366px) {
        min-width: 70px !important;
        padding: 12px 18px !important;
        font-size: 13px !important;
    }

    // 笔记本屏幕优化
    @media (max-width: 1440px) and (min-width: 1200px) {
        min-width: 68px !important;
        padding: 11px 16px !important;
    }
}

// 批量操作栏样式
.batch-operations {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    padding: 12px 16px;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    
    .batch-info {
        color: #626aef;
        font-weight: 500;
        font-size: 14px;
        margin-right: auto;
    }
    
    .el-button {
        height: 32px;
        padding: 8px 16px;
        font-size: 13px;
        
        &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
    }
}

// 状态筛选按钮样式
.status-filter {
    display: flex;
    gap: 8px;
    align-items: center;

    .status-btn {
        padding: 6px 12px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        background: #fff;
        color: #606266;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
            color: #626aef;
            border-color: #626aef;
            background: #f5f7fa;
        }

        &.active {
            color: #fff !important;
            background: #626aef !important;
            border-color: #626aef !important;
            box-shadow: 0 2px 4px rgba(98, 106, 239, 0.3);
        }
    }
}

// 输入框样式
::v-deep .el-input__wrapper {
    background-color: rgba(250, 252, 251, 1);
}

//表格样式
::v-deep .el-table {
    --el-table-header-bg-color: rgba(235, 236, 240, 1);
}

::v-deep .el-table thead {
    color: #444;
}

//分页样式
.pagination {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding-top: 10px;
    border-top: 1px solid #98989848;
}

::v-deep .el-pagination.is-background .el-pager li.is-active {
    background-color: #000 !important;
}

// 深度选择器优化Element Plus按钮样式
:deep(.el-button--small) {
    // 确保所有小按钮都有合适的点击区域
    min-height: 32px;
    line-height: 1.4;
}

// 表格操作列优化
:deep(.el-table__fixed-right) {
    .el-table__cell {
        padding: 8px 12px; // 增加单元格内边距
    }
}

// 针对触摸设备的优化
@media (pointer: coarse) {
    .action-btn {
        min-width: 75px !important;
        padding: 12px 16px !important;
        min-height: 36px !important;
    }

    .detail-btn {
        min-width: 80px !important;
        padding: 14px 20px !important;
        min-height: 38px !important;
    }
}
</style>
